
package com.example.casper.Experiment2024.ui.theme;

import android.os.Bundle;
import android.widget.Button;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import com.example.casper.Experiment2024.R;



public class Hello3810Activity extends AppCompatActivity {
    private MyAdapter adapter;
    private ActivityResultLauncher<Intent> someActivityLauncher;

    // ... 省略其他代码 ...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化RecyclerView和Adapter
        // ...

        // 设置ActivityResultLauncher
        someActivityLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode() == RESULT_OK) {
                Intent data = result.getData();
                if (data != null) {
                    String bookName = data.getStringExtra("bookName");
                    double price = data.getDoubleExtra("price", 0.0);
                    boolean isEdit = data.getBooleanExtra("isEdit", false);
                    int position = data.getIntExtra("position", -1);

                    if (isEdit) {
                        // 修改数据
                        adapter.editBook(position, bookName, price);
                    } else {
                        // 添加数据
                        adapter.addBook(bookName, price);
                    }
                }
            }
        });

        // 设置Adapter的ContextMenu监听
        adapter.setOnContextItemClickListener((position, action) -> {
            switch (action) {
                case "add":
                    addBook(position);
                    break;
                case "edit":
                    editBook(position);
                    break;
                case "delete":
                    deleteBook(position);
                    break;
            }
        });
    }

    private void addBook(int position) {
        Intent intent = new Intent(this, AddEditBookActivity.class);
        intent.putExtra("isEdit", false);
        someActivityLauncher.launch(intent);
    }

    private void editBook(int position) {
        Book book = adapter.getItem(position);
        Intent intent = new Intent(this, AddEditBookActivity.class);
        intent.putExtra("bookName", book.getName());
        intent.putExtra("price", book.getPrice());
        intent.putExtra("isEdit", true);
        intent.putExtra("position", position);
        someActivityLauncher.launch(intent);
    }

    private void deleteBook(int position) {
        new AlertDialog.Builder(this)
                .setTitle("删除图书")
                .setMessage("确定要删除这本书吗？")
                .setPositiveButton("确定", (dialog, which) -> {
                    adapter.deleteBook(position);
                })
                .setNegativeButton("取消", (dialog, which) -> {
                    // do nothing
                })
                .show();
    }
}



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_hello3810);
        for (int i = 0; i < 10; i++) {
            // 假设按钮的ID为 button_number_0, button_number_1, ..., button_number_9
            int buttonId = getResources().getIdentifier("button_number_" + i, "id", getPackageName());
            Button button = findViewById(buttonId);
            if (button != null) { // 检查按钮是否为null，以防ID找不到
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // 将数字追加到clickedNumber字符串中
                        clickedNumber += String.valueOf(i);
                    }
                });
            }
        }

        // 获取Clean按钮的引用并设置点击事件监听器
        Button cleanButton = findViewById(R.id.button_clean);
        cleanButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 显示确认对话框
                AlertDialog.Builder builder = new AlertDialog.Builder(Hello3810Activity.this);
                builder.setMessage("Are you sure to clean the number?")
                        .setCancelable(false)
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // 用户点击确定按钮，清空clickedNumber
                                clickedNumber = "";
                            }
                        })
                        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // 用户点击取消按钮，不处理
                            }
                        });
                AlertDialog alert = builder.create();
                alert.show();
            }
        });

        // 获取Input按钮的引用并设置点击事件监听器
        Button inputButton = findViewById(R.id.button_input);
        inputButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 显示Toast消息
                Toast.makeText(Hello3810Activity.this, "You have input number " + clickedNumber, Toast.LENGTH_SHORT).show();
            }
        });
    }
    ConstraintLayout constraintLayout = findViewById(R.id.constraintLayout);
        View buttonToKeep = findViewById(R.id.buttonToKeep);

        // Remove all views except the one we want to keep
        removeAllViewsExcept(constraintLayout, buttonToKeep);
    }

    private void removeAllViewsExcept(ViewGroup parent, View toKeep) {
        int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = parent.getChildAt(i);
            if (child != toKeep) {
                parent.removeView(child);
                i--; // Adjust index since we removed a view
                childCount--; // Optionally, you can skip this line if you know childCount is accurate enough
            }
        }
    }
}
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });


    }
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_hello_3810);

    RecyclerView recyclerView = findViewById(R.id.recycler_view_the_books);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));

    List<RecyclerViewBookAdapter.Book> bookList = new ArrayList<>();
    // Populate your bookList with data
    bookList.add(new RecyclerViewBookAdapter.Book("https://example.com/book1_cover.jpg", "Book 1"));
    bookList.add(new RecyclerViewBookAdapter.Book("https://example.com/book2_cover.jpg", "Book 2"));
    // Add more books as needed

    RecyclerViewBookAdapter adapter = new RecyclerViewBookAdapter(this, bookList);
    recyclerView.setAdapter(adapter);
}@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
    // 绑定数据
    // ...

    // 注册ContextMenu
    holder.itemView.setOnCreateContextMenuListener(this);
}

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    menu.add(Menu.NONE, ADD_ITEM_ID, Menu.NONE, "添加");
    menu.add(Menu.NONE, EDIT_ITEM_ID, Menu.NONE, "修改");
    menu.add(Menu.NONE, DELETE_ITEM_ID, Menu.NONE, "删除");
}

@Override
public boolean onContextMenuItemClick(MenuItem item) {
    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    int position = info.position;

    switch (item.getItemId()) {
        case ADD_ITEM_ID:
            // 调用Activity的添加方法
            addBook(position);
            return true;
        case EDIT_ITEM_ID:
            // 调用Activity的修改方法
            editBook(position);
            return true;
        case DELETE_ITEM_ID:
            // 调用Activity的删除方法
            deleteBook(position);
            return true;
    }
    return false;
}public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

    private List<Book> bookList;
    private Context context;
    private OnContextItemClickListener listener;

    public interface OnContextItemClickListener {
        void onItemClick(int position, String action);
    }

    public MyAdapter(List<Book> bookList, Context context) {
        this.bookList = bookList;
        this.context = context;
    }

    public void setOnContextItemClickListener(OnContextItemClickListener listener) {
        this.listener = listener;
    }

    // 添加图书
    public void addBook(String bookName, double price) {
        int position = bookList.size(); // 默认添加到最后
        bookList.add(new Book(bookName, price, R.drawable.default_book_image));
        notifyItemInserted(position); // 局部刷新
    }

    // 添加图书到指定位置后
    public void addBook(int position, String bookName, double price) {
        bookList.add(position + 1, new Book(bookName, price, R.drawable.default_book_image));
        notifyItemInserted(position + 1); // 局部刷新
    }

    // 修改图书
    public void editBook(int position, String bookName, double price) {
        Book book = bookList.get(position);
        book.setName(bookName);
        book.setPrice(price);
        notifyItemChanged(position); // 局部刷新
    }

    // 删除图书
    public void deleteBook(int position) {
        bookList.remove(position);
        notifyItemRemoved(position); // 局部刷新
    }

    // 省略其他代码 ...
}public class AddEditBookActivity extends AppCompatActivity {

    private EditText bookNameEditText;
    private EditText priceEditText;
    private boolean isEdit;
    private int position;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_edit_book);

        bookNameEditText = findViewById(R.id.bookNameEditText);
        priceEditText = findViewById(R.id.priceEditText);

        Intent intent = getIntent();
        isEdit = intent.getBooleanExtra("isEdit", false);


        if (isEdit) {
            String bookName = intent.getStringExtra("bookName");
            double price = intent.getDoubleExtra("price", 0.0);
            position = intent.getIntExtra("position", -1);
            bookNameEditText.setText(bookName);
            priceEditText.setText(String.valueOf(price));
        }

        findViewById(R.id.saveButton).setOnClickListener(v -> {
            String bookName = bookNameEditText.getText().toString();
            double price = Double.parseDouble(priceEditText.getText().toString());

            Intent resultIntent = new Intent();
            resultIntent.putExtra("bookName", bookName);
            resultIntent.putExtra("price", price);
            resultIntent.putExtra("isEdit", isEdit);
            if (isEdit) {
                resultIntent.putExtra("position", position);
            }
            setResult(RESULT_OK, resultIntent);
            finish();
        });
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ViewPager2 viewPager = findViewById(R.id.view_pager);
        TabLayout tabLayout = findViewById(R.id.tab_layout);

        MyFragmentAdapter adapter = new MyFragmentAdapter(this);
        viewPager.setAdapter(adapter);

        new TabLayoutMediator(tabLayout, viewPager, (tab, position) -> {
            switch (position) {
                case 0:
                    tab.setText("图书");
                    break;
                case 1:
                    tab.setText("搜索");
                    break;
                case 2:
                    tab.setText("地图");
                    break;
            }
        }).attach();
    }
    public MyFragmentAdapter(@NonNull FragmentActivity fragmentActivity) {
        super(fragmentActivity);
    }

    @NonNull
    @Override
    public Fragment createFragment(int position) {
        switch (position) {
            case 0:
                return new BookListFragment();
            case 1:
                return new WebViewFragment();
            case 2:
                return new TencentMapFragment();
            default:
                return new BookListFragment();
        }
    }

    @Override
    public int getItemCount() {
        return 3; // Tab的数量
    }
}
